package fr.generali.sas.extras.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

public class MDCServletFilter implements Filter {

	 private static Logger logger = LoggerFactory.getLogger(MDCServletFilter.class);
	 
	 private static final String ID_CLIENT="idClient";
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		String url = httpRequest.getRequestURL().toString();
		String requestedPage = url.substring(url.indexOf(httpRequest.getContextPath()) + httpRequest.getContextPath().length() + 1);
		logger.debug("url : {} requestedPage : " , new Object[]{url,requestedPage});
		
		
		/*
		 * /public/v4/sas/recupererFluxClient/{codeIntermediaire}/{idClient}
		 * /public/v4/sas/recupererFluxAgence/{codeIntermediaire}
		 * /public/v4/sas/poursuivreRecuperationFlux/{codeIntermediaire}/{numeroReservation}/{fromId}
		 * /public/v4/sas/acquitterSucces/{codeIntermediaire}/{numeroReservation}
		 * /public/v4/sas/acquitterEchec/{codeIntermediaire}/{numeroReservation}
		 */
		
		StringBuilder message = new StringBuilder(256);
		message.append("[codeIntermediaire=").append(getCodeIntermediaire(request));
		message.append("| codePortefeuille=").append(getCodePortefeuille(request));
		message.append("| numReservation=").append(getNumreservation(request));
		message.append("| idClient=").append(getIdClient(request)).append("]");
		logger.debug("message=" + message);
		
		try {
            MDC.put("userContexte", message.toString());
            chain.doFilter(request, response);
        } finally {
            MDC.remove("userContexte");
        }

	}

	private Object getNumreservation(ServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

	private Object getIdClient(ServletRequest request) {
		return null;
	}

	private Object getCodePortefeuille(ServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

	private Object getCodeIntermediaire(ServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
